const http = require("../../../utils/http");

Page({
  data: {
    classroomTypes: ['普通多媒体教室', '智慧多媒体教室'],
    typeIndex: 0,
    showNextDay: false,
    timeSlots: [],
    selectedTimes: [],
    availableClassrooms: [],
    selectedClassroomIndex: -1,
    selectedClassroom: null,
    applicantName: '',
    userNumber: '',
    phone: '',
    reason: ''
  },

  onLoad() {
    this.initTimeSlots();
  },

  initTimeSlots() {
    const now = new Date();
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();
    const currentTime = currentHour * 60 + currentMinute;

    const baseSlots = [{
        field: 'time1',
        label: '7:30-8:00',
        start: 450,
        isNextDay: false
      },
      {
        field: 'time2',
        label: '8:10-9:50',
        start: 490,
        isNextDay: false
      },
      {
        field: 'time3',
        label: '10:05-11:40',
        start: 605,
        isNextDay: false
      },
      {
        field: 'time4',
        label: '12:00-14:30',
        start: 720,
        isNextDay: false
      },
      {
        field: 'time5',
        label: '14:30-16:05',
        start: 870,
        isNextDay: false
      },
      {
        field: 'time6',
        label: '16:15-17:55',
        start: 975,
        isNextDay: false
      },
      {
        field: 'time7',
        label: '17:55-19:00',
        start: 1075,
        isNextDay: false
      },
      {
        field: 'time8',
        label: '19:00-21:00',
        start: 1140,
        isNextDay: false
      },
      {
        field: 'time9',
        label: '7:30-8:00',
        start: 450,
        isNextDay: true
      },
      {
        field: 'time10',
        label: '8:10-9:50',
        start: 490,
        isNextDay: true
      },
      {
        field: 'time11',
        label: '10:05-11:40',
        start: 605,
        isNextDay: true
      },
      {
        field: 'time12',
        label: '12:00-14:30',
        start: 720,
        isNextDay: true
      },
      {
        field: 'time13',
        label: '14:30-16:05',
        start: 870,
        isNextDay: true
      },
      {
        field: 'time14',
        label: '16:15-17:55',
        start: 975,
        isNextDay: true
      },
      {
        field: 'time15',
        label: '17:55-19:00',
        start: 1075,
        isNextDay: true
      },
      {
        field: 'time16',
        label: '19:00-21:00',
        start: 1140,
        isNextDay: true
      }
    ];

    const timeSlots = baseSlots.map(slot => {
      const isToday = !slot.isNextDay;
      const disabled = isToday && slot.start < currentTime;
      return {
        ...slot,
        selected: false,
        disabled
      };
    });

    this.setData({
      timeSlots
    });
  },

  toggleNextDay() {
    this.setData({
      showNextDay: !this.data.showNextDay
    });
  },

  onInput(e) {
    const field = e.currentTarget.dataset.field;
    this.setData({
      [field]: e.detail.value
    });
  },

  onTypeChange(e) {
    this.setData({
      typeIndex: Number(e.detail.value)
    }, () => {
      this.fetchAvailableClassrooms();
    });
  },

  onTimeTap(e) {
    const field = e.currentTarget.dataset.field;
    const clickedItem = this.data.timeSlots.find(item => item.field === field);

    if (clickedItem.disabled) {
      wx.showToast({
        title: '该时间段已过，无法选择',
        icon: 'none'
      });
      return;
    }
    const timeSlots = this.data.timeSlots.map(item => {
      if (item.field === field) {
        return {
          ...item,
          selected: !item.selected
        };
      }
      return item;
    });

    const selectedTimes = timeSlots
      .filter(item => item.selected)
      .map(item => item.field + (item.isNextDay ? '_next' : ''));

    this.setData({
      timeSlots,
      selectedTimes
    }, () => {
      this.fetchAvailableClassrooms();
    });
  },

  onClassroomTap(e) {
    const classroom = e.currentTarget.dataset.classroom;
    this.setData({
      selectedClassroom: classroom
    });
  },

  fetchAvailableClassrooms() {
    const {
      classroomTypes,
      typeIndex,
      selectedTimes
    } = this.data;
    if (!selectedTimes.length) return;

    const classType = classroomTypes[typeIndex];

    http('/classroom/available', {
      classType,
      timeFields: selectedTimes
    }, 'POST', {}).then(res => {
      if (res.data.success) {
        this.setData({
          availableClassrooms: res.data.classrooms,
          selectedClassroomIndex: -1
        });
      } else {
        wx.showToast({
          title: '获取教室失败',
          icon: 'none'
        });
      }
    });
  },

  submitApplication() {
    const {
      applicantName,
      userNumber,
      phone,
      reason,
      selectedTimes,
      classroomTypes,
      typeIndex,
      selectedClassroom
    } = this.data;

    if (!selectedClassroom || !applicantName || !userNumber || !phone || !reason || selectedTimes.length === 0) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    const classType = classroomTypes[typeIndex];

    const postData = {
      applicantName,
      userNumber,
      userPhoneNumber: phone,
      reason,
      classroomNumber: selectedClassroom,
      classroomType: classType,
      timeFields: selectedTimes,
      state: '待审批'
    };

    http('/classroom/submitApplication', postData, 'POST', {}).then(res => {
      if (res.data.conflict) {
        const conflictTimes = res.data.conflictTimes.map(field => {
          const labelMap = {
            'time1': '7:30-8:00',
            'time2': '8:10-9:50',
            'time3': '10:05-11:40',
            'time4': '12:00-14:30',
            'time5': '14:30-16:05',
            'time6': '16:15-17:55',
            'time7': '17:55-19:00',
            'time8': '19:00-21:00'
          };
          const base = field.replace('_next', '');
          const label = labelMap[base] || base;
          return label + (field.includes('_next') ? '（次日）' : '');
        }).join('\n');

        wx.showModal({
          title: '部分时间冲突',
          content: `以下时间段的申请已经存在并且待管理员审批中：\n${conflictTimes}\n教室号：${res.data.conflictClassroom}\n是否仍要提交？`,
          confirmText: '仍要提交',
          cancelText: '取消',
          success: modalRes => {
            if (modalRes.confirm) {
              http('/classroom/submitApplication', {
                ...postData,
                ignoreConflict: true
              }, 'POST', {}).then(res2 => {
                if (res2.data.success) {
                  wx.showToast({
                    title: '提交成功',
                    icon: 'success'
                  });
                  wx.navigateBack({
                    delta: 1 // 返回上一页
                  })
                } else {
                  wx.showToast({
                    title: res2.data.message || '提交失败',
                    icon: 'none'
                  });
                }
              });
            }
          }
        });
      } else if (res.data.success) {
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        });
        wx.navigateBack({
          delta: 1 // 返回上一页
        })
      } else {
        wx.showToast({
          title: res.data.message || '提交失败',
          icon: 'none'
        });
      }
    });
  }
});